<?php
if (!defined('ROOT')) exit('Can\'t Access !');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/16
 * Time: 16:42
 */

/**
 * 银行账户操作模块控制器
 * Class mod_account
 * @author zhangcn <wecontact@foxmail.com>
 */
class mod_account extends module_class
{
    /**
     * 创建账户
     *
     * @return bool 返回布尔值
     * @throws \Dibi\Exception
     */
    public function create()
    {
        if (is_post()) {
            // 账户用户
            $uid = (int) $this->input()->post('uid');
            if ($uid < 1) {
                fail('User error');
            }

            // 创建账户
            $ret = $this->mod->createAccount($uid);

            if ($ret === false)
            {
                logger("Account insert fail.uid:$uid");
                fail('Account create failed');
            }

            success('Account create successful');
        }
    }

    /**
     * 冻结账户（关闭账户）
     */
    public function freeze()
    {
        if (is_post()) {
            // 银行账户
            $account = $this->input()->post('account');
            if (empty($account)) {
                fail('Account error');
            }

            // 冻结账户
            $ret = $this->mod->freezeAccount($account);

            if ($ret === false)
            {
                logger("Account freeze fail.account:$account");
                fail('Account freeze failed');
            }

            success('Account freeze successful');
        }
    }

    /**
     * 获取账户余额
     *
     * @throws \Dibi\Exception
     */
    public function getBalance()
    {
        if (is_post()) {
            // 银行账户
            $account = $this->input()->post('account');
            if (empty($account)) {
                fail('Account error');
            }

            // 获取账户信息
            $result = $this->mod->getAccount($account);

            if ($result === false)
            {
                logger("Balance get fail.account:$account");
                fail('Balance get failed');
            }

            success([
                'account' => $result->name,
                'balance' => $result->balance
            ]);
        }
    }

    /**
     * 账户取款
     *
     * @throws \Dibi\Exception
     */
    public function withdraw()
    {
        if (is_post()) {
            // 银行账户
            $account = $this->input()->post('account');
            if (empty($account)) {
                fail('Account error');
            }

            // 取款金额
            $amount = $this->input()->post('amount');
            if ($amount < MIN_AMOUNT || $amount > MAX_AMOUNT) {
                fail('Amount error');
            }

            // 查询账户
            $result = $this->mod->getAccount($account);

            if ($result === false)
            {
                logger("Withdraw fail.account:$account");
                fail('Withdraw failed');
            }

            // 检查账户是否已被冻结（关闭）
            if ($result->is_freeze == 1) {
                fail('Account is freeze');
            }

            $time = time();
            $create_time = date('Y-m-d H:i:s', $time);

            // 检查账户余额是否不足
            if ($result->balance < $amount) {
                fail([
                    'message' => 'Credit is running low',
                    'account' => $result->name,
                    'amount' => $amount,
                    'balance' => $result->balance,
                    'time' => $create_time
                ]);
            }

            // 开启事务
            $this->db->begin();

            // 更新取款数据
            $balance = $result->balance - $amount;
            $ret = $this->mod->withholdUpdate($account, $balance);
            if ($ret == false) {
                fail('Withhold update fail');
            }

            // 流水数据
            $data = array(
                'amt' => $amount,
                'bill_id' => guidv4(),
                'bill_info' => '账户取款',
                'bill_user' => $result->uid,
                'bill_time' => $create_time,
                'bill_type' => BILL_WITHDRAW,
                'old_balance' => $result->balance,
                'src_ip' => getip()
            );

            // 创建流水
            $ret = $this->mod->createBill($account, $data);
            if ($ret === false) {
                $this->db->rollback(); // 回滚事务
                fail('Bill insert fail');
            }

            // 提交事务
            $this->db->commit();

            success([
                'account' => $result->name,
                'amount' => $amount,
                'balance' => $balance,
                'time' => $create_time
            ]);
        }
    }

    /**
     * 账户存款
     *
     * @throws \Dibi\Exception
     */
    public function deposit()
    {
        if (is_post()) {
            // 银行账户
            $account = $this->input()->post('account');
            if (empty($account)) {
                fail('Account error');
            }

            // 存款金额
            $amount = $this->input()->post('amount');
            if ($amount < MIN_DEPOSIT || $amount > MAX_DEPOSIT) {
                fail('Amount error');
            }

            // 查询账户信息
            $result = $this->mod->getAccount($account);

            if ($result === false)
            {
                logger("Account get fail.account:$account");
                fail('Account get failed');
            }

            // 检查账户是否已被冻结（关闭）
            if ($result->is_freeze == 1) {
                fail('Account is freeze');
            }

            // 取出用户和账户余额
            $uid = $result->uid;
            $old_balance = $result->balance;

            // 开启事务
            $this->db->begin();

            $time = time();
            $create_time = date('Y-m-d H:i:s', $time);

            // 更新账户存款
            $balance = $result->balance + $amount;
            $result = $this->mod->depositUpdate($account, $balance);

            if ($result === false)
            {
                logger("Deposit fail.account:$account");
                fail('Deposit failed');
            }

            // 流水数据
            $data = array(
                'amt' => $amount,
                'bill_id' => guidv4(),
                'bill_info' => '账户存款',
                'bill_user' => $uid,
                'bill_time' => $create_time,
                'bill_type' => BILL_DEPOSIT,
                'old_balance' => $old_balance,
                'src_ip' => getip()
            );

            // 创建流水
            $ret = $this->mod->createBill($account, $data);
            if ($ret === false) {
                $this->db->rollback(); // 回滚事务
                fail('Bill insert fail');
            }

            // 提交事务
            $this->db->commit();

            success([
                'account' => $result->name,
                'amount' => $amount,
                'balance' => $balance,
                'time' => $create_time
            ]);
        }
    }

    /**
     * 账户转账
     *
     * @throws \Dibi\Exception
     */
    public function transfer()
    {
        if (is_post()) {
            // 转账金额
            $amount = $this->input()->post('amount');
            if ($amount < MIN_TRANSFER || $amount > MAX_TRANSFER) {
                fail('Amount error');
            }

            // 转账账户
            $account = $this->input()->post('account');
            if (empty($account)) {
                fail('Account error');
            }

            // 获取转账账户信息
            $result = $this->mod->getAccount($account);

            if ($result === false)
            {
                logger("Account get fail.account:$account");
                fail('Account get failed');
            }

            // 检查转账账户是否已被冻结（关闭）
            if ($result->is_freeze == 1) {
                fail('Account is freeze');
            }

            // 记录转账账户信息
            $uid = $result->uid;
            $balance = $result->balance;
            
            // 设置转账账户余额
            $this->mod->balance = $balance;

            // 收款账户
            $to_account = $this->input()->post('to_account');
            if (empty($to_account)) {
                fail('To Account error');
            }

            // 判断收款账户与转账账户是否同一账户
            if ($to_account == $account) {
                fail([
                    'message' => 'Transfer fail',
                    'account' => $account,
                    'to_account' => $to_account,
                    'amount' => $amount,
                ]);
            }

            // 获取收款账户信息
            $result = $this->mod->getAccount($to_account);

            if ($result === false)
            {
                logger("To Account get fail.account:$to_account");
                fail('To Account get failed');
            }

            // 检查收款账户是否已被冻结（关闭）
            if ($result->is_freeze == 1) {
                fail('To Account is freeze');
            }

            // 记录收款账户信息
            $to_uid = $result->uid;

            // 设置收款账户余额
            $this->mod->to_balance = $result->balance;

            // 执行时间
            $time = time();
            $create_time = date('Y-m-d H:i:s', $time);

            // 获取当天转账金额总和
            $total_transfer = $this->mod->getCurrentDayTransfer();

            // 判断当天转账金额是否大于设置的最大值
            if (($total_transfer + $amount) > TRANSFER_LIMIT) {
                fail('Transfer exceeding quota');
            }

            // 开启事务
            $this->db->begin();

            // 判断是否同一用户的不同账户
            if ($uid == $to_uid) {
                // 转账手续费用
                $transfer_fee = 0;

                // 检查转账账户可用余额
                if (($amount - $balance) > 0) {
                    fail([
                        'message' => 'Credit is running low',
                        'account' => $account,
                        'transfer_fee' => $transfer_fee,
                        'amount' => $amount,
                        'balance' => $balance
                    ]);
                }
                
                // 账户转账
                $result = $this->mod->transferAccount($account, $to_account, $amount);
            }
            else {
                // 转账手续费用
                $transfer_fee = TRANSFER_FEE;

                // 检查转账账户可用余额
                $total_amount = $amount + TRANSFER_FEE;
                if (($total_amount - $balance) > 0) {
                    fail([
                        'message' => 'Credit is running low',
                        'account' => $account,
                        'transfer_fee' => $transfer_fee,
                        'amount' => $amount,
                        'balance' => $balance
                    ]);
                }

                // 获取转账授权
                $url = 'http://handy.travel/test/success.json';
                $res = curl_send($url, 'post');
                $res = json_decode($res);
                
                if ($res->status == 'success') {
                    // 账户转账
                    $result = $this->mod->transferDiffAccount($account, $to_account, $amount);
                } else {
                    fail('Authorization fail');
                }
            }

            // 转账失败
            if ($result === false) {
                $this->db->rollback(); // 回滚事务
                fail([
                    'message' => 'Transfer fail',
                    'account' => $account,
                    'to_account' => $to_account,
                    'amount' => $amount,
                ]);
            }

            // 流水数据
            $data = array(
                'amt' => $amount,
                'bill_id' => guidv4(),
                'bill_info' => '账户转账',
                'bill_user' => $uid,
                'bill_time' => $create_time,
                'bill_type' => BILL_TRANSFER,
                'old_balance' => $balance,
                'src_ip' => getip()
            );

            // 创建流水
            $ret = $this->mod->createBill($account, $data);
            if ($ret === false) {
                $this->db->rollback(); // 回滚事务
                fail('Bill insert fail');
            }

            // 提交事务
            $this->db->commit();

            success([
                'account' => $account,
                'to_account' => $to_account,
                'amount' => $amount,
                'transfer_fee' => $transfer_fee,
                'balance' => $this->mod->balance,
                'time' => $create_time
            ]);
        }
    }
}